﻿namespace Bundler
{
    using Microsoft.Ajax.Utilities;
    using System;
    using System.Web;

    public class CssMinify : IMinify
    {
        #region Public Methods and Operators

        public virtual void Process(BundleResponse response)
        {
            response.RequestAction = () => SetHeaders(response.Bundle.Options.EnableOptimizations);
            BundleResponseHelper.GetContent(response, response.Bundle.Options.Css.ReplaceUrls);
            MinifyContent(response);
        }

        public virtual void SetHeaders(bool optimize)
        {
            var context = HttpContext.Current;
            if (context == null)
                return;

            context.Response.ContentType = "text/css";

            if (!optimize)
                return;
            
            context.Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
            context.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(365));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
            context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

            GzipCompression.Compress(context);
        }

        public virtual void MinifyContent(BundleResponse response)
        {
            if (!response.Bundle.Options.EnableOptimizations)
                return;

            //it is common for CSS frameworks to do something like this to avoid minifier stripping out their comment-header
            //but i like smaller files kthx
            response.Content = response.Content.Replace("/*!", "/*");

            var cruncher = new Minifier();
            response.Content = cruncher.MinifyStyleSheet(response.Content, new CssSettings
            {
                IgnoreAllErrors = true
            });
        }

        #endregion
    }
}